import axios from 'axios'
// import { Message, MessageBox } from 'element-ui'
import { MessageBox } from 'element-ui'
import { removeToken, removeUserInfo, getToken } from '@/utils/auth'
import { api } from '@/ipconfig'
console.log(api)
// import baseURL from '@/ipconfig'
// 创建axios实例
const service = axios.create({
  timeout: 40000, // 请求超时时间
  withCredentials: true
})
// service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
// request拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const status = response.status
    const res = response.data
    if (status == 200 || status == 201 || status == 204) {
      return response.data
    } else if (status == 401) { // 登录到期
      // 50008:非法的token;  50014:Token 过期了;
      MessageBox.confirm(
        res.resMsg,
        '提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        removeUserInfo()
        removeToken()
        location.reload()
      }).catch(() => {
        removeUserInfo()
        removeToken()
        location.reload()
      })
      return Promise.reject(res)
    } else if (res.resCode === 20003) { // 20003 请求无权限
      return Promise.reject(res)
    } else {
      // Message({
      //   message: (res.resMsg ? res.resMsg : '网络错误，请重新再试！'),
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      return Promise.reject(res)
    }
  },
  error => {
    // console.log(JSON.stringify(error.config), JSON.stringify(error.response))
    // Message({
    //   message: (error.resMsg ? error.resMsg : '网络错误，请重新再试！'),
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

export default service
